package com.qf.system.role.controller;

import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.qf.system.menu.model.Menu;
import com.qf.system.menu.service.MenuService;
import com.qf.system.role.model.Role;
import com.qf.system.role.service.RoleService;
import com.qf.util.PageData;
import com.qf.util.RightsHelper;
import com.qf.util.common.Const;
import com.qf.util.common.Tools;
import com.qf.util.controller.BaseController;
import com.qf.util.entity.Page;

@Controller
@RequestMapping("/qjqwmain/role")
public class RoleController extends BaseController{
	@Resource(name="menuService")
	private MenuService menuService;
	@Resource(name="roleService")
	private RoleService roleService;
	
	
   private static	Log log=LogFactory.getLog(RoleController.class);
	/**
	 * 权限(增删改查)
	 */
	@RequestMapping(value="/qx")
	public ModelAndView qx(String msg)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			roleService.updateQx(msg,pd);
			
			mv.setViewName("/WEB-INF/system/save_result");
			mv.addObject("msg","success");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * K权限
	 */
	@RequestMapping(value="/kfqx")
	public ModelAndView kfqx()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			String msg = pd.getString("msg");
			roleService.updateKFQx(msg,pd);
			
			mv.setViewName("/WEB-INF/system/save_result");
			mv.addObject("msg","success");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * c权限
	 */
	@RequestMapping(value="/gysqxc")
	public ModelAndView gysqxc()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			String msg = pd.getString("msg");
			roleService.gysqxc(msg,pd);
			
			mv.setViewName("/WEB-INF/system/save_result");
			mv.addObject("msg","success");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping
	public ModelAndView list(String role_id)throws Exception{
			ModelAndView mv = this.getModelAndView();
			PageData pd = new PageData();
			pd = this.getPageData();
			
			String roleId = role_id;
			if(roleId == null || "".equals(roleId)){
				pd.put("role_id", "1");
			}else{
				
				pd.put("role_id", role_id);
			}
			List<Role> roleList = roleService.listAllRoles();				//列出所有部门
			List<Role> roleList_z = roleService.listAllRolesByPId(pd);		//列出此部门的所有下级
			
			List<PageData> kefuqxlist = roleService.listAllkefu(pd);		//管理权限列表
			List<PageData> gysqxlist = roleService.listAllGysQX(pd) ;		//用户权限列表
			
			/*调用权限*/
			this.getHC(); //================================================================================
			/*调用权限*/
			
			pd = roleService.findObjectById(pd);							//取得点击部门
			log.info("查询了一次权限");
			mv.addObject("pd", pd);
			mv.addObject("kefuqxlist", kefuqxlist);
			mv.addObject("gysqxlist", gysqxlist);
			mv.addObject("roleList", roleList);
			mv.addObject("roleList_z", roleList_z);
			mv.setViewName("/WEB-INF/system/role/role_list");
		
		return mv;
	}
	
	/**
	 * 新增页面
	 */
	@RequestMapping(value="/toAdd")
	public ModelAndView toAdd(Page page){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			mv.setViewName("/WEB-INF/system/role/role_add");
			mv.addObject("pd", pd);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 保存新增信息
	 */
	@RequestMapping(value="/add")
	public ModelAndView add()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			String parent_id = pd.getString("parent_id");		//父类角色id
			pd.put("role_id", parent_id);			
			if("0".equals(parent_id)){
				pd.put("rights", "");
			}else{
				String rights = roleService.findObjectById(pd).getString("rights");
				pd.put("rights", (null == rights)?"":rights);
			}

			pd.put("qx_id", "");
			
			String UUID = this.get32UUID();
			
				pd.put("gl_id", UUID);
				pd.put("fx_qx", 0);				//发信权限
				pd.put("fw_qx", 0);				//服务权限
				pd.put("qx1", 0);				//操作权限
				pd.put("qx2", 0);				//产品权限
				pd.put("qx3", 0);				//预留权限
				pd.put("qx4", 0);				//预留权限
				roleService.saveKeFu(pd);		//保存到K权限表
			
				pd.put("u_id", UUID);
				pd.put("c1", 0);				//每日发信数量
				pd.put("c2", 0);
				pd.put("c3", 0);
				pd.put("c4", 0);
				pd.put("q1", 0);				//权限1
				pd.put("q2", 0);				//权限2
				pd.put("q3", 0);
				pd.put("q4", 0);
				roleService.saveGYSQX(pd);		//保存到G权限表
				pd.put("qx_id", UUID);
			
			pd.put("role_id", UUID);
			pd.put("add_qx", "0");
			pd.put("del_qx", "0");
			pd.put("edit_qx", "0");
			pd.put("cha_qx", "0");
			roleService.add(pd);
			mv.addObject("msg","success");
		} catch(Exception e){
			logger.error(e.toString(), e);
			mv.addObject("msg","failed");
		}
		mv.setViewName("redirect:/qjqwmain/role");
		return mv;
	}
	
	/**
	 * 请求编辑
	 */
	@RequestMapping(value="/toEdit")
	public ModelAndView toEdit( String role_id )throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			pd.put("role_id", role_id);
			pd = roleService.findObjectById(pd);
			
			mv.setViewName("/WEB-INF/system/role/role_edit");
			mv.addObject("pd", pd);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 编辑
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(PrintWriter writer)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			pd = roleService.edit(pd);
			mv.addObject("msg","success");
			writer.write("success");
			writer.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
			mv.addObject("msg","failed");
		}
		mv.setViewName("/WEB-INF/system/save_result");
		return mv;
	}
	
	/**
	 * 请求角色菜单授权页面
	 */
	@RequestMapping(value="/auth")
	public String auth(@RequestParam String role_id,Model model)throws Exception{
		
		try{
			List<Menu> menuList = menuService.listAllMenu();
			Role role = roleService.getRoleById(role_id);
			String roleRights = role.getRights();
			if(Tools.notEmpty(roleRights)){
				for(Menu menu : menuList){
					menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMenu_id()));
					if(menu.isHasMenu()){
						List<Menu> subMenuList = menuService.listSubMenuByParentId(menu.getMenu_id());
						if(subMenuList!=null &&subMenuList.size()>0){
							menu.setSubMenu(subMenuList);
						for(Menu sub : subMenuList){
							System.out.println(RightsHelper.testRights(roleRights, sub.getMenu_id())+":MenuName"+sub.getMenu_name());
							sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMenu_id()));
						}
						}
					}
				}
			}
		
			JSONArray arr = JSONArray.fromObject(menuList);
			String json = arr.toString();
			json = json.replaceAll("menu_id", "id").replaceAll("menu_name", "name").replaceAll("subMenu", "nodes").replaceAll("hasMenu", "checked");
			model.addAttribute("zTreeNodes", json);
			model.addAttribute("roleId", role_id);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return "/WEB-INF/system/role/authorization";
	}
	
	/**
	 * 请求角色按钮授权页面
	 */
	@RequestMapping(value="/button")
	public ModelAndView button(@RequestParam String role_id,@RequestParam String msg,Model model)throws Exception{
		ModelAndView mv = this.getModelAndView();
		try{
			List<Menu> menuList = menuService.listAllMenu();
			Role role = roleService.getRoleById(role_id);
			
			String roleRights = "";
			if("add_qx".equals(msg)){
				roleRights = role.getAdd_qx();
			}else if("del_qx".equals(msg)){
				roleRights = role.getDel_qx();
			}else if("edit_qx".equals(msg)){
				roleRights = role.getEdit_qx();
			}else if("cha_qx".equals(msg)){
				roleRights = role.getCha_qx();
			}
			
			if(Tools.notEmpty(roleRights)){
				for(Menu menu : menuList){
					menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMenu_id()));
					if(menu.isHasMenu()){
						List<Menu> subMenuList = menu.getSubMenu();
						for(Menu sub : subMenuList){
							sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMenu_id()));
						}
					}
				}
			}
			JSONArray arr = JSONArray.fromObject(menuList);
			String json = arr.toString();
			//System.out.println(json);
			json = json.replaceAll("menu_id", "id").replaceAll("menu_name", "name").replaceAll("subMenu", "nodes").replaceAll("hasMenu", "checked");
			mv.addObject("zTreeNodes", json);
			mv.addObject("roleId", role_id);
			mv.addObject("msg", msg);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		mv.setViewName("/WEB-INF/system/role/role_button");
		return mv;
	}
	
	/**
	 * 保存角色菜单权限
	 */
	@RequestMapping(value="/auth/save")
	public void saveAuth(@RequestParam String role_id,@RequestParam String menuIds,PrintWriter out)throws Exception{
		PageData pd = new PageData();
		try{
			if(null != menuIds && !"".equals(menuIds.trim())){
				BigInteger rights = RightsHelper.sumRights(Tools.str2StrArray(menuIds));
				System.out.println(Tools.str2StrArray(menuIds).toString()+"rights");
				Role role = roleService.getRoleById(role_id);
				role.setRights(rights.toString());
				roleService.updateRoleRights(role);
				pd.put("rights",rights.toString());
			}else{
				Role role = new Role();
				role.setRights("");
				role.setRole_id(role_id);
				roleService.updateRoleRights(role);
				pd.put("rights","");
			}
				
				pd.put("roleId", role_id);
				roleService.setAllRights(pd);
			
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}
	
	/**
	 * 保存角色按钮权限
	 */
	@RequestMapping(value="/roleButton/save")
	public void orleButton(@RequestParam String role_id,@RequestParam String menuIds,@RequestParam String msg,PrintWriter out)throws Exception{
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			if(null != menuIds && !"".equals(menuIds.trim())){
				BigInteger rights = RightsHelper.sumRights(Tools.str2StrArray(menuIds));
				pd.put("value",rights.toString());
			}else{
				pd.put("value","");
			}
			pd.put("role_id", role_id);
			roleService.updateQx(msg,pd);
			
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void deleteRole(@RequestParam String role_id,PrintWriter out)throws Exception{
		PageData pd = new PageData();
		try{
			pd.put("role_id", role_id);
			List<Role> roleList_z = roleService.listAllRolesByPId(pd);		//列出此部门的所有下级
			if(roleList_z.size() > 0){
				out.write("false");
			}else{
				
				List<PageData> userlist = roleService.listAllUByRid(pd);
				List<PageData> appuserlist = roleService.listAllAppUByRid(pd);
				if(userlist.size() > 0 || appuserlist.size() > 0){
					out.write("false2");
				}else{
				roleService.deleteRoleById(role_id);
				roleService.deleteKeFuById(role_id);
				roleService.deleteGById(role_id);
				out.write("success");
				}
			}
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}
	
	
	
	/* ===============================权限================================== */
	@SuppressWarnings("unchecked")
	public void getHC(){
		ModelAndView mv = this.getModelAndView();
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		Map<String, Integer> map = (Map<String, Integer>)session.getAttribute(Const.SESSION_QX);
		mv.addObject(Const.SESSION_QX,map);	//按钮权限
		List<Menu> menuList = (List<Menu>)session.getAttribute(Const.SESSION_menuList);
		mv.addObject(Const.SESSION_menuList, menuList);//菜单权限
	}
	/* ===============================权限================================== */

}
